package com.muyu.file.controller;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.vod.model.v20170321.*;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.file.FileUtils;
import com.muyu.common.system.domain.SysFile;
import com.muyu.file.service.VodService;
import com.muyu.file.utils.ConstantVodUtils;
import com.muyu.file.utils.InitVodCilent;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 视频上传
 */
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;



    //上传视频到阿里云
    @PostMapping("/uploadAlyiVideo")
    public Result uploadAlyiVideo(@RequestParam MultipartFile file) throws Exception {
        SysFile sysFile = new SysFile();

            // 上传视频和获取视频信息的代码逻辑
            String videoId = vodService.uploadVideoAly(file);
           sysFile.setVideoId(videoId);
        System.out.println("videoId = " + videoId);
            String url = getUrl(videoId);
        System.out.println("url = " + url);
            JSONObject jsonObject = new JSONObject(url);
            String requestId = jsonObject.getString("RequestId");
            String playURL = jsonObject.getJSONObject("PlayInfoList")
                    .getJSONArray("PlayInfo")
                    .getJSONObject(0)
                    .getString("PlayURL");
            sysFile.setName(FileUtils.getName(requestId));
            sysFile.setUrl(playURL);
            return Result.success(sysFile);
//        } catch (Exception e) {
//            // 捕获异常并返回详细错误信息
//            return Result.error("上传视频时发生错误: " + e.getMessage());
//        }
//        return Result.success(videoId);
    }
    //根据视频id删除阿里云视频
    @DeleteMapping("removeAlyVideo/{id}")
    public Result<String> removeAlyVideo(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodCilent.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            return  Result.success(id,"删除视频");
        }catch(Exception e) {
            e.printStackTrace();
           return Result.error("删除视频失败");
        }
    }

    //删除多个阿里云视频的方法
    //参数多个视频id  List videoIdList
    @DeleteMapping("delete-batch")
    public String deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return  "删除视频成功";
    }


    /**
     * 获取视频播放凭证
     * @param id 视频id
     * @return
     * @throws Exception
     */
    @GetMapping("/getPlayAuth/{id}")
    public GetVideoPlayAuthResponse getPlayAuth(@PathVariable String id) throws Exception {
        try {
            // 创建初始化对象
            DefaultAcsClient client =
                    InitVodCilent.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 向request设置视频id
            request.setVideoId(id);
            // 调用方法得到凭证
            // 凭证
            return client.getAcsResponse(request);
        }catch (Exception e){
            throw new Exception("获取凭证失败！");
        }
    }

    @GetMapping("/getPlayAuthIA/{id}")
    public String getUrl(@PathVariable String id) throws Exception {
        IAcsClient client = InitVodCilent.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("vod.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2017-03-21");
        request.setSysAction("GetPlayInfo");
        request.putQueryParameter("VideoId", id);
        CommonResponse response = client.getCommonResponse(request);

        // 获取 JSON 响应字符串
        String jsonResponse = response.getData();
        System.out.println("JSON Response: " + jsonResponse);

        // 解析 JSON 响应
        JSONObject jsonObject = new JSONObject(jsonResponse);

        // 安全地获取 Status 和 AuditStatus 字段
        String videoStatus = jsonObject.optString("Status", "");
        String auditStatus = jsonObject.optString("AuditStatus", "");

        // 检查是否存在 Code 和 Message 字段，处理 API 请求失败的情况
        String code = jsonObject.optString("Code", "");
        String message = jsonObject.optString("Message", "");

        if (!code.isEmpty()) {
            throw new ClientException("API 请求失败: " + message);
        }

        // 检查视频状态和审核状态
        if ("Transcoding".equals(videoStatus)) {
            throw new ClientException("视频正在转码中，请稍后再试");
        }

        if ("Init".equals(auditStatus)) {
            throw new ClientException("视频尚未完成审核，请稍后再试");
        }

        // 返回 JSON 响应
        return jsonResponse;
    }

    private String getVideoPlayInfoAfterProcessing(String videoId) throws Exception {
        int retries = 0;
        // 轮询最多重试 5 次
        while (retries < 5) {
            // 调用原本的 getUrl 方法获取视频的 JSON 响应
            String jsonResponse = getUrl(videoId);
            JSONObject jsonObject = new JSONObject(jsonResponse);

            // 获取视频状态和审核状态
            String videoStatus = jsonObject.optString("Status", "");
            String auditStatus = jsonObject.optString("AuditStatus", "");

            // 如果视频转码完成并且审核通过，返回响应
            if ("UploadSucc".equals(videoStatus) && "Pass".equals(auditStatus)) {
                return jsonResponse;
            }

            retries++; // 递增重试次数
            Thread.sleep(10000); // 每 10 秒检查一次
        }

        throw new Exception("视频处理未完成，请稍后再试"); // 超过最大重试次数，抛出异常
    }

}

